
const { spawn, fork } = require('child_process');
const { sockets } = require('./webSocket');
module.exports.cmdPromise = (params, cmd, args, options = {}) => {
    return new Promise((resolve, reject) => {
        if (params.option === 'decompress' || params.option === 'compress') {
            // 压缩进程
            const child = spawn(cmd, args, options);
            child.stderr.on('data', (data) => {
                const percentMatch = data.toString().match(/(\d+)%/);
                if (percentMatch) {
                    const progress = parseInt(percentMatch[1], 10);
                    if (progress >= 0 && progress <= 100) {
                        const targetSocket = sockets.get(params.socketId);
                        targetSocket.emit('send', { fileName: params.fileName, progress, option: params.option });
                        console.log(`正在${params.type}中 --- ${progress}%`);
                    }
                }
                if (data.includes('ERROR')) {
                    console.warn(`压缩失败: ${data}`);
                    const targetSocket = sockets.get(params.socketId);
                    targetSocket.emit('send', { fileName: params.fileName, progress: 0, option: 'compress', status: 'error' });
                }
            });
            child.stdout.on('data', (data) => { });
            child.on('close', (code) => {
                if (code === 0) {
                    resolve();
                }
            });
            child.on('error', reject);
        } else {
            // node脚本进程
            const child = fork(cmd);
            child.send({ fileName: params.fileName, startPage: params.startPage, endPage: params.endPage })//传参数给子进程
            child.on('message', (message) => {
                if (message.progress) {
                    // 传进度给前端
                    const { current, all } = message
                    const targetSocket = sockets.get(params.socketId);
                    targetSocket.emit('send', { fileName: params.fileName, progress: (current / all).toFixed(2) * 100, option: params.option });
                    console.log(`正在${params.type}中 --- ${(current / all).toFixed(2) * 100}%`);
                } else {
                    resolve();
                }
            })
        }
    });
}